<template>
  <div class="container">
    <div class="header">
      <logo class="logo" />
      <span class="title">
        实时球赛数据
        <i v-if="listLoading" class="el-icon-loading" style="float:right"></i>
      </span>
      <div class="menu">
        <div class="audio-btn">
          <el-tooltip class="item" effect="dark" content="比赛过程10分钟内进2球时播放声音" placement="bottom-end">
            <el-checkbox v-model="tenMinusAudioChecked">10分钟进2球声音</el-checkbox>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="整个比赛过程中，有过10分钟内进2球的球赛高亮背景色"
            placement="bottom-end"
          >
            <el-checkbox v-model="tenMinsGoalBackgroundChecked">10分钟进2球背景</el-checkbox>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="比赛过程10分钟内进2球的球赛放到区域①" placement="top">
            <el-checkbox v-model="tenMins2GoalPut1Checked">10分钟进2放①区</el-checkbox>
          </el-tooltip>

          <br />
          <br />
          <el-tooltip
            class="item"
            effect="dark"
            content="优先净胜球降序排序，净胜球一样的球赛按总射门比降序排序"
            placement="bottom-end"
          >
            <el-checkbox v-model="goalRateChecked">叠加总射门比排序</el-checkbox>
          </el-tooltip>
          <el-checkbox v-model="goalAudioChecked">进球提示音</el-checkbox>
          <!-- <el-checkbox v-model="panelAudioChecked">区域升降</el-checkbox> -->
          <el-checkbox v-model="weworkChecked">推送消息</el-checkbox>
          <el-checkbox v-model="notStartChecked">未比赛数据</el-checkbox>
          <br />
          <br />
          <el-tooltip
            class="item"
            effect="dark"
            content="双方都进球，总>=3，且60~74分钟有进球，第75分钟发信息：买大于"
            placement="bottom-end"
          >
            <el-checkbox v-model="oneChecked">放①区可选</el-checkbox>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="半场结束，双方进球且进球数在 4~5 之间，中场发信息：中场买小于；下半场再进球2，发信息：剧本立马买大于"
            placement="bottom-end"
          >
            <el-checkbox v-model="twoChecked">放②区可选</el-checkbox>
          </el-tooltip>
        </div>
        <el-button
          class="refresh"
          type="primary"
          size="mini"
          icon="el-icon-refresh"
          :loading="listLoading"
          @click="getList()"
        >手动刷新</el-button>
        <!--  <el-button
          class="refresh"
          type="primary"
          size="mini"
          icon="el-icon-refresh"
          @click="testChat()"
        >test</el-button>-->
      </div>
    </div>
    <div style="padding-top:20px">
      <div class="living">
        <span class="time">数据更新时间：{{ refreshTime }}</span>
        <i class="el-icon-timer" style="color:#fe9828"></i>正在进行中的比赛
        <span v-if="dataCopy">(共 {{ dataCopy && dataCopy.length }} 场）</span>
      </div>
      <s-table
        :data="data"
        :page-size="100"
        :showPagination="false"
        :cell-class-name="tableCellClassName"
        :span-method="arraySpanMethod"
        empty-text="当前时段没有比赛"
      >
        <el-table-column label="序号" width="90px" align="center">
          <template slot-scope="{row}">
            <el-popover
              v-if="row._panel"
              placement="top-start"
              :title="row.title"
              width="400"
              trigger="hover"
              :content="row.panelTip"
            >
              <span slot="reference">{{ row.title }}</span>
            </el-popover>
            <span v-else>{{row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赛事" width="160px" align="left">
          <template slot-scope="{row}">
            <div class="event-icon" :style="{'background-image':row.eventIcon}" />
            <span>{{ row.eventName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赛程" width="80px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.beginTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="80px" align="center">
          <template slot-scope="{row}">
            <span style="color:#f3692c;">{{row.status}}</span>
          </template>
        </el-table-column>
        <el-table-column label="主场球队" align="center">
          <template slot-scope="{row}">
            <div v-if="row.toggleAnimate===1" class="event-icon ball" />
            <span>{{ row.homeTeam }}</span>
          </template>
        </el-table-column>
        <el-table-column label="比分" width="100px" align="center">
          <template slot-scope="{row}">
            <el-popover trigger="hover" placement="right" class="goalTabel">
              <el-table :data="row.goalGridData">
                <el-table-column width="160" property="goalTeam" label="进球球队"></el-table-column>
                <el-table-column width="100" align="center" property="goalTime" label="时间(分)"></el-table-column>
                <el-table-column width="140" align="center" property="goalMan" label="进球球员"></el-table-column>
              </el-table>
              <span slot="reference" style="color:red;font-weight:600">{{row.score}}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="客场球队" align="center">
          <template slot-scope="{row}">
            <div v-if="row.toggleAnimate===2" class="event-icon ball" />
            <span>{{ row.guestTeam }}</span>
          </template>
        </el-table-column>
        <el-table-column label="半场" width="100px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.half }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总射比" width="80px" align="center">
          <template slot-scope="{row}">
            <span style="color:#333;font-weight:600">{{row.shotRate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="射正比" width="80px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.frontShotRate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80px" align="center">
          <template slot-scope="{row}">
            <el-tooltip placement="top" width="100" trigger="hover" content="星标操作在下次数据更新时见效">
              <i v-if="row.marked" @click="handleMarked(row,false)" class="el-icon-star-on mark"></i>
              <i v-else @click="handleMarked(row,true)" class="el-icon-star-off mark"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </s-table>
      <div class="not-start" v-if="notStartChecked">
        <i class="el-icon-football"></i>
        未开始的比赛 (共 {{ notStartData && notStartData.data.length }} 场）
      </div>
      <s-table
        v-if="notStartChecked"
        :data="notStartData"
        :page-size="100"
        :showPagination="false"
        :max-height="450"
        :columns="columns"
        style="margin-bottom: 30px;"
      >
        <template #indexSlot="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
        <template #eventIconSlot="{row}">
          <div class="event-icon" :style="{'background-image':row.eventIcon}" />
          <span>{{ row.eventName }}</span>
        </template>
      </s-table>
    </div>
    <vue-plyr style="display:none" ref="plyr">
      <audio>
        <source src="~static/audio/0.mp3" type="audio/mp3" />
      </audio>
    </vue-plyr>
    <vue-plyr style="display:none" ref="plyr1">
      <audio>
        <source src="~static/audio/1.mp3" type="audio/mp3" />
      </audio>
    </vue-plyr>
    <vue-plyr style="display:none" ref="plyr2">
      <audio>
        <source src="~static/audio/2.mp3" type="audio/mp3" />
      </audio>
    </vue-plyr>
    <vue-plyr style="display:none" ref="plyr3">
      <audio>
        <source src="~static/audio/3.mp3" type="audio/mp3" />
      </audio>
    </vue-plyr>
  </div>
</template>

<script>
import Logo from '~/components/Logo.vue'
import STable from '~/components/Table'
import { post } from '@/shared/request'
import remove from 'lodash/remove'
import uniq from 'lodash/uniq'
import { REQ_INTERVAL_TIME } from '@/shared/constants'
import { parseTime } from '@/shared/utils'
import { handleLivesData, sortAndRenderByRules } from '~/pages/usercase'
import ChatRobot from '@/shared/wework/chat'

export default {
  components: {
    Logo,
    STable,
  },
  data() {
    this.intervalTimer = null
    return {
      tenMinusAudioChecked: true,
      goalAudioChecked: false,
      tenMinsGoalBackgroundChecked: true,
      tenMins2GoalPut1Checked: false,
      goalRateChecked: true,
      panelAudioChecked: false,
      notStartChecked: false,
      oneChecked: false,
      twoChecked: false,
      weworkChecked: false,
      markClsObject: {
        'el-icon-star-on': false,
        'el-icon-star-off': true,
      },
      columns: [
        {
          label: '序号',
          field: 'index',
          width: 90,
          scopedSlots: { customRender: 'indexSlot' },
        },
        {
          label: '赛事',
          field: 'eventName',
          width: 160,
          scopedSlots: { customRender: 'eventIconSlot' },
        },
        {
          label: '开始时间',
          field: 'beginTime',
          width: 100,
        },
        {
          label: '状态',
          field: 'status',
          width: 80,
        },
        {
          label: '主场球队',
          field: 'homeTeam',
        },

        {
          label: '比分',
          field: 'score',
          width: 100,
        },
        {
          label: '客场球队',
          field: 'guestTeam',
        },
      ],
      data: null,
      dataCopy: null,
      diffPanelIds: [],
      refreshTime: '',
      notStartData: null,
      listLoading: false,
      listQuery: {},
    }
  },
  computed: {
    player() {
      return this.$refs.plyr.player
    },
    player1() {
      return this.$refs.plyr1.player
    },
    player2() {
      return this.$refs.plyr2.player
    },
    player3() {
      return this.$refs.plyr3.player
    },
  },
  watch: {
    tenMinusAudioChecked(value) {
      if (process.client) {
        window.tenMinusAudioChecked = value
      }
      if (value) {
        window.playAudio(3)
      }
    },
    goalAudioChecked(value) {
      if (process.client) {
        window.goalAudioChecked = value
      }
      if (value) {
        window.playAudio(2)
      }
    },
    goalRateChecked(value) {
      if (process.client) {
        window.goalRateChecked = value
      }
    },
    tenMins2GoalPut1Checked(value) {
      if (process.client) {
        window.tenMins2GoalPut1Checked = value
      }
    },
    weworkChecked(value) {
      if (process.client) {
        window.weworkChecked = value
      }
    },
    oneChecked(value) {
      if (process.client) {
        window.oneChecked = value
      }
    },
    twoChecked(value) {
      if (process.client) {
        window.twoChecked = value
      }
    },
    panelAudioChecked(value) {
      if (process.client) {
        window.panelAudioChecked = value
      }
      if (value) {
        window.playAudio(1)
      }
    },
  },
  created() {
    if (process.client) {
      window.tenMinusAudioChecked = this.tenMinusAudioChecked
      window.goalAudioChecked = this.goalAudioChecked
      window.tenMins2GoalPut1Checked = this.tenMins2GoalPut1Checked
      window.weworkChecked = this.weworkChecked
      window.oneChecked = this.oneChecked
      window.twoChecked = this.twoChecked
      window.goalRateChecked = this.goalRateChecked
      window.panelAudioChecked = this.panelAudioChecked
    }
  },
  mounted() {
    // 提供调试用
    if (process.client) {
      window.playAudio = (type = 0) => {
        if (type === 0) {
          this.player.play()
        } else if (type === 1) {
          this.player1.play()
        } else if (type === 2) {
          this.player2.play()
        } else if (type === 3) {
          this.player3.play()
        }
      }
      window._testChat = () => {
        this.testChat()
      }
    }
    this.getList()
    if (this.intervalTimer) {
      clearInterval(this.intervalTimer)
      this.intervalTimer = null
    }
    this.intervalTimer = setInterval(() => {
      if (!this.listLoading) {
        this.getList()
      }
    }, REQ_INTERVAL_TIME)

    this.player.on('event', () => console.log('audio event fired'))
  },
  destroyed() {
    if (this.intervalTimer) {
      clearInterval(this.intervalTimer)
      this.intervalTimer = null
    }
  },
  methods: {
    testChat() {
      const robotid = '7543cdd5-f746-4136-b73d-102f956598f2'
      const robot = new ChatRobot(robotid)
      const eventName = 'eventName'
      const teamName = 'teamName'
      const text1 = 'text1'
      const text2 = 'text2'
      const msg = `【${eventName}】比赛进球了\n  >进球方: <font color="info">${teamName}</font> \n  >条件:  <font color="comment">${text1}</font> \n  >建议操作:  <font color="info">${text2}</font>`
      robot.sendMdMsg(msg)
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (row._panel && columnIndex === 0) {
        return [1, 11]
      }
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      // bg-ball :进球效果
      // panel-title :区域行背景色
      // bg1: 晋升第一第二区域提示颜色
      const homeGoalColumn = row.toggleAnimate === 1 && columnIndex == 4 // 主队进球
      const awayGoalColumn = row.toggleAnimate === 2 && columnIndex == 6 // 客队进球
      if (row._panel) return 'panel-title'

      if (
        row.goal2_in_ten &&
        this.tenMinsGoalBackgroundChecked &&
        (columnIndex == 4 || columnIndex == 5 || columnIndex == 6)
      ) {
        // 10分钟进2球的球赛
        if (awayGoalColumn || homeGoalColumn) {
          return 'bg1 bg-ball'
        } else {
          return 'bg1'
        }
      } else if (awayGoalColumn || homeGoalColumn) {
        // 其他区域进球
        return 'bg-ball'
      }
      /*
      // 原来有升降区域背景色逻辑
      if (
        (row._firstPanel || row._secondPanel) &&
        this.diffPanelIds.includes(row.id) &&
        (columnIndex == 4 || columnIndex == 5 || columnIndex == 6)
      ) {
        // 晋升第一第二区域提示颜色
        if (awayGoalColumn || homeGoalColumn) {
          return 'bg1 bg-ball'
        } else {
          return 'bg1'
        }
      } else if (awayGoalColumn || homeGoalColumn) {
        // 其他区域进球
        return 'bg-ball'
      } */
    },
    getList(evt) {
      this.listLoading = true
      this.listQuery.notStartChecked = this.notStartChecked
      post('/game/list', this.listQuery)
        .then((result) => {
          this.dataCopy = result.lives
          const liveData = handleLivesData(result.lives)
          // const liveData = handleLivesData(mockliveData)
          const [sortData, diffPanelIds] = sortAndRenderByRules(liveData)
          // console.log('diffPanelIds=', JSON.stringify(diffPanelIds))
          // this.diffPanelIds = diffPanelIds
          // console.log(sortData)
          this.data = {
            data: sortData,
            pageInfo: {
              totalSize: 9999,
              totalPages: 1,
              size: 9999,
              first: true,
              last: false,
              number: 0,
            },
          }
          this.notStartData = {
            data: result.notStart,
            pageInfo: {
              totalSize: 9999,
              totalPages: 1,
              size: 9999,
              first: true,
              last: false,
              number: 0,
            },
          }
          this.refreshTime = parseTime(new Date())
          this.listLoading = false
        })
        .catch((err) => {
          this.listLoading = false
        })
    },
    handleMarked(row, isMark) {
      const { id } = row
      this.$nextTick(() => {
        row.marked = !row.marked
        // row.secret = Date.now()
      })
      if (process.client) {
        let markedList = window.sessionStorage.getItem('markedList') || '[]'
        markedList = JSON.parse(markedList)
        if (isMark) {
          markedList.push(id)
        } else {
          remove(markedList, (item) => item === id)
        }
        window.sessionStorage.setItem(
          'markedList',
          JSON.stringify(uniq(markedList))
        )
      }
    },
  },
}
</script>

<style>
.el-table {
  font-size: 16px;
}
.bg1 {
  background: #f0f9eb;
}
.bg2 {
  background: oldlace;
}
.bg3 {
  background: #77bb88;
  color: #606266;
}
.bg-ball {
  background: #409eff;
  color: #fff;
}
.panel-title {
  padding: 2px 0 !important;
  background: #ebeef5;
}
.orange {
  background: orange;
}
.container {
  min-height: 100vh;
  background: #eee;
}
.audio-btn {
  display: inline-block;
  margin-right: 20px;
  font-size: 13px;
  color: #606166;
  /* margin-top: 5px; */
}
.header {
  position: relative;
  top: 0;
  height: 90px;
  width: 1200px;
  margin: 0 auto;
}
.logo {
  width: 90px;
  height: 90px;
}
.refresh {
  float: right;
}
.menu {
  display: inline-block;
  position: absolute;
  right: 0;
  top: 30px;
}
.living .time {
  position: absolute;
  right: 0;
  top: 10px;
  margin-right: 10px;
  font-size: 12px;
  color: rgb(16, 135, 117);
  font-weight: 400;
}
.sino-table {
  /* position: absolute; */
  width: 1220px;
  margin: 0 auto;
  margin-bottom: 26px;
}
.mark {
  font-size: 20px;
  cursor: pointer;
}
.living,
.not-start {
  position: relative;
  margin: 15px auto;
  font-size: 20px;
  text-align: center;
  font-weight: 100;
  width: 1220px;
}

.not-start {
  margin-top: 30px;
}
.title {
  position: absolute;
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: inline-block;
  font-weight: 300;
  font-size: 50px;
  color: #35495e;
  letter-spacing: 1px;
  height: 90px;
  padding-top: 20px;
  padding-left: 15px;
}
.title > .el-icon-loading {
  font-size: 25px;
  margin-top: 18px;
}
.event-icon {
  display: inline-block;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  margin: 0 3px 0;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
}
.ball {
  background-image: url('http://ww1.sinaimg.cn/large/940e68eegy1gg770z8ykrj200o00o0si.jpg');
}
.goalTabel {
  max-height: 500px;
  overflow-y: auto;
}
</style>
